package com.google.code.HomeSeek;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;

import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {

	static final String LOG_ID = "HomeSeek.ScreenReceiver";

	TelephonyManager telephone = null;

	void goHome(Context ctx) {
		Intent myIntent = new Intent(Intent.ACTION_MAIN); 
		myIntent.addCategory(Intent.CATEGORY_HOME); 
		myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		ctx.startActivity(myIntent);
		Log.d(LOG_ID, "Sent Home intent");
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		SharedPreferences settings = context.getSharedPreferences(HomeSeekActivity.PREFS_NAME, context.MODE_PRIVATE);
		boolean goHome = settings.getBoolean(HomeSeekActivity.GO_HOME_PREF, true);
		String action = intent.getAction();
		if (action.equals(Intent.ACTION_SCREEN_OFF)) {
			// screen turned off - go home
			Log.d(LOG_ID, "Received screen off " + (goHome?"- going home":"- do nothing"));
			if (goHome) {
				boolean ignoreDuringCalls = settings.getBoolean(HomeSeekActivity.IGNORE_DURING_CALLS_PREF, true);
				boolean inCall = (telephone != null) && (telephone.getCallState() == telephone.CALL_STATE_OFFHOOK);
				if (!(ignoreDuringCalls && inCall)) {
					goHome(context);
				}
			}
		} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
			// on boot, start our service
			Log.d(LOG_ID, "Received boot completed " + (goHome?"- start service":"- do nothing"));
			if (goHome) {
				Intent serviceIntent = new Intent(context, InstallerService.class);
				context.startService(serviceIntent);
			}
		}
	}
}
